<template>
  <div class="gis-map">
     <main-map height="100%"   @map-loaded="mapLoaded" :showSearchInput="false" >
       <left-bar :visible.sync="showleft"/>
       <right-bar :point="point" :visible.sync="show"/>
     </main-map>
  </div>
</template>
<script>
// import MeetingVideoLayer from './components/meeting-video';
import LeftBar from './components/left-bar';
import RightBar from './components/right-bar';
export default {
  components: {
    // MeetingVideoLayer,
    LeftBar, RightBar
  },
  data() {
    return {
      showleft: true,
      show: true,
      showCreatMeeting: false,
      showmeetingVideo: false,
      showcontact: false,
      showselectMeetingLayer: false,
      pointList: [],
      map: null,
      AMap: null,
      infoWindow: null,
      AMapUI: null,
      point: {},
      pathSimplifierIns: null
    };
  },
  created() {
    // AMapUILoader(AMapUI => {
    //   this.AMapUI = AMapUI;
    //   console.log(`   this.AMapUI`, this.AMapUI);
    // });
  },
  mounted() {
    document.querySelector('.el-card__body').style.padding = 0;
  },
  destroyed() {
    document.querySelector('.el-card__body').style.padding = '10px';
  },
  methods: {
    mapLoaded(map, AMap, AMapUI) {
      console.log(`AMapUI`, AMapUI);
      this.AMapUI = AMapUI;
      this.map = map;
      this.AMap = AMap;
      // this.map.setCenter([120.019039, 33.353613]);
      this.drawBounds();
      this.getPointList();
    },
    getInfoContent(point) {
      const className = point.isOverdue === 1 ? 'popup' : 'popup'; // popupRed
      return `<div class="${className}">${point.pointName}</div>`;
    },
    addInfoWindow() {
      const AMap = this.AMap;
      const offset = new AMap.Pixel(-46, -60);
      const infoList = this.pointList.map((point, index) => {
        const marker = new AMap.Marker({
          clickable: true, // 点位是否可点击
          offset, // 设置点标记偏移量
          position: [point.longitude, point.latitude], // new AMap.LngLat(point.longitude, point.latitude),
          content: this.getInfoContent(point),
          extData: point
        });
        return marker;
      });
      this.map.add(infoList);
    },
    getPointList() {
      const params = {
        url: `/api/ems/station/list/map`,
        type: 'post',
        params: {

        }
      };
      this.$ajax(params).then(resp => {
        this.pointList = resp;
        this.addMarker();
        this.addInfoWindow();
        if (resp.length) {
          this.point = resp[0];
        }
      });
    },
    getMarkContent(point) {
      // 是否超期 0 否 1 是
      // private Integer isOverdue;
      // const color = point.isOverdue === 1 ? 'red' : '#67C23A';style="color:${color};"
      const className = point.isOverdue === 1 ? 'car-icon' : 'car-icon j-primary-color';
      return `<svg class="${className}"  aria-hidden="true" ><use xlink:href="#icon-xiaoche"></use></svg>`;
    },
    addMarker() {
      const AMap = this.AMap;
      const offset = new AMap.Pixel(-16, -30);
      const markerList = this.pointList.map((point, index) => {
        const marker = new AMap.Marker({
          clickable: true, // 点位是否可点击
          offset, // 设置点标记偏移量
          position: [point.longitude, point.latitude], // new AMap.LngLat(point.longitude, point.latitude),
          content: this.getMarkContent(point),
          extData: point
        });
        marker.on('click', _ => {
          this.show = true;
          this.$nextTick(_ => {
            this.point = point;
          });
        });
        marker.on('rightclick', _ => {
          if (!this.pathSimplifierIns) {
            this.getCarTravel(point);
          } else {
            this.pathSimplifierIns.setData([]);
            this.pathSimplifierIns = null;
          }
        });

        marker.on('mouseover', e => {
          // this.infoWindow.setContent(point.pointName);
          // this.infoWindow.open(this.map, [point.longitude, point.latitude]);
        });
        marker.on('mouseout', e => {
          // this.infoWindow.close();
        });
        return marker;
      });
      this.map.add(markerList);
      this.map.setFitView(markerList);// 视口自适应
    },
    drawBounds() {
      const AMap = this.AMap;
      const map = this.map;
      // var opts = {
      //   subdistrict: 0, // 获取边界不需要返回下级行政区
      //   extensions: 'all', // 返回行政区边界坐标组等具体信息
      //   level: 'province' // 查询行政级别为 市
      // };
      // const district = new AMap.DistrictSearch(opts);
      // district.search('江苏省', function(status, result) {
      //   var polygons = [];
      //   var bounds = result.districtList[0].boundaries;
      //   if (bounds) {
      //     for (var i = 0, l = bounds.length; i < l; i++) {
      //       // 生成行政区划polygon
      //       var polygon = new AMap.Polygon({
      //         strokeWeight: 1,
      //         path: bounds[i],
      //         fillOpacity: 0.4,
      //         fillColor: '#80d8ff',
      //         strokeColor: '#0091ea'
      //       });
      //       polygons.push(polygon);
      //     }
      //   }
      //   map.add(polygons);
      //   map.setFitView(polygons);// 视口自适应
      // });
      new AMap.DistrictSearch({
        extensions: 'all',
        subdistrict: 0
      }).search('江苏省', function(status, result) {
        // 外多边形坐标数组和内多边形坐标数组
        var outer = [
          new AMap.LngLat(-360, 90, true),
          new AMap.LngLat(-360, -90, true),
          new AMap.LngLat(360, -90, true),
          new AMap.LngLat(360, 90, true)
        ];
        var holes = result.districtList[0].boundaries;

        var pathArray = [
          outer
        ];
        pathArray.push.apply(pathArray, holes);
        var polygon = new AMap.Polygon({
          pathL: pathArray,
          strokeColor: '#00eeff',
          strokeWeight: 1,
          fillColor: '#71B3ff',
          fillOpacity: 0.5
        });
        polygon.setPath(pathArray);
        map.add(polygon);
      });
    },
    // 获取车辆轨迹
    getCarTravel(point) {
      const startTime = this.$moment().format('YYYY-MM-DD HH:mm:ss');
      const endTime = this.$moment().add(-2, 'h').format('YYYY-MM-DD HH:mm:ss');
      const params = {
        url: `/api/ems/point/position/page/list`,
        type: 'post',
        params: {
          endTime,
          pointCode: point.pointCode,
          startTime
        }
      };
      this.$ajax(params).then(resp => {
        console.log(`getCarTravel`, resp);
        const { result, rows } = resp;
        if (result) {
          if (rows.length) {
            this.travel(rows);
          } else {
            this.$message({
              message: '近两小时暂无车辆历史轨迹信息',
              type: 'warning'
            });
          }
        }
      });
    },
    travel(rows) {
      const AMapUI = this.AMapUI;
      const map = this.map;
      AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier, $) => {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！');
          return;
        }
        // var emptyLineStyle = {
        //   lineWidth: 0,
        //   fillStyle: null,
        //   strokeStyle: null,
        //   borderStyle: null
        // };
        this.pathSimplifierIns = new PathSimplifier({
          zIndex: 100,
          // autoSetFitView:false,
          map: map, // 所属的地图实例

          getPath: function(pathData, pathIndex) {
            return pathData.path;
          },
          getHoverTitle: function(pathData, pathIndex, pointIndex) {
            return null;
          },
          renderOptions: {
            renderAllPointsIfNumberBelow: 100 // 绘制路线节点，如不需要可设置为-1
            // 将点、线相关的style全部置emptyLineStyle
            // pathLineStyle: emptyLineStyle,
            // pathLineSelectedStyle: emptyLineStyle,
            // pathLineHoverStyle: emptyLineStyle,
            // keyPointStyle: emptyLineStyle,
            // startPointStyle: emptyLineStyle,
            // endPointStyle: emptyLineStyle,
            // keyPointHoverStyle: emptyLineStyle,
            // keyPointOnSelectedPathLineStyle: emptyLineStyle
          }
        });
        const path = rows.map(v => {
          return [v.longi, v.lat];
        });

        // window.pathSimplifierIns = this.pathSimplifierIns;

        this.pathSimplifierIns.setData([{
          name: '测试',
          path: path.reverse()

        }]);
        // initRoutesContainer(d);
        // function onload() {
        //   pathSimplifierIns.renderLater();
        // }
        // function onerror(e) {
        //   alert('图片加载失败！');
        // }
        var navg1 = this.pathSimplifierIns.createPathNavigator(0, {
          loop: true,
          speed: 1000
          // pathNavigatorStyle: {
          //   width: 24,
          //   height: 24,
          //   // 使用图片
          //   // content: PathSimplifier.Render.Canvas.getImageContent('./imgs/plane.png', onload, onerror),
          //   strokeStyle: null,
          //   fillStyle: null,
          //   // 经过路径的样式
          //   pathLinePassedStyle: {
          //     lineWidth: 6,
          //     strokeStyle: 'black',
          //     dirArrowStyle: {
          //       stepSpace: 15,
          //       strokeStyle: 'red'
          //     }
          //   }
          // }
        });
        navg1.start();
      });
    },
    addContact() {
      this.showcontact = true;
      this.$nextTick(_ => {
        this.$refs.contactLayer.openDialog();
        // this.$refs.rightBar.mainVideo.hideVideo();
      });
    },
    creatMeeting() {
      this.showCreatMeeting = true;
      this.$nextTick(_ => {
        this.$refs.creatMeeting.openDialog();
      });
    },
    addMeeting() {
      this.showselectMeetingLayer = true;
      this.$nextTick(_ => {
        this.$refs.selectMeetingLayer.openDialog();
      });
    },
    onSuccess() {
      this.$nextTick(_ => {
        this.$refs.toolBtn.getMeetingList();
      });
    }
  },
  computed: {
    siteContentViewHeight() {
      var height = this.documentClientHeight - 70 - 30 - 2;
      return height + 'px';
    },
    documentClientHeight: {
      get() { return this.$store.state.common.documentClientHeight; }
    }
  }

};
</script>

<style lang="scss" >
// $primary-light-bgcolor:  #bad4ec;
// $primary-color:#196FBF;

// .j-primary-color {
//   color:$primary-color !important;
// }
// .j-primary-bgcolor {
//   background-color:$primary-color !important;
// }
// .j-primary-light-bgcolor {
//   background-color: $primary-light-bgcolor !important;
//  }
// .j-primary-border-color {
//   border-color:$primary-color !important;
// }
// .j-primary-light-border-color {
//   border-color: $primary-light-bgcolor !important;
// }
.gis-map{
  height: 100%;
  .amap-info-close{
    display: none;
  }
  .car-icon {
    width: 32px;
    height: 30px;
    fill: currentColor;
    overflow: hidden;
    color: red;
  }
  .popup{
    white-space: nowrap;
    padding: 5px;
    background: white;
    border-radius: 4px;
    width: 100px;
    text-align: center;
  }
  .popup:after{
    content: "";   
    position: absolute;
    left: 38px;
    // margin-left: -8px;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    bottom: -8px;
    // left: 50%;
    border-top: 8px solid #fff;
  }
  .popupRed:after{
     border-top: 8px solid red;
  }
}
</style>